package com.jolink.omiis.wechat.api.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.jolink.omiis.wechat.api.ICustomerService;
import com.jolink.omiis.wechat.keys.IPreferences;

public class CustomerService extends WeChatApiBaseService implements ICustomerService {
	private static Logger logger = LoggerFactory.getLogger(CustomerService.class);

	@Override
	public String send(String appId, String message) {
		long t1 = System.currentTimeMillis();
		if (StringUtils.isEmpty(appId)) {
			JsonObject root = new JsonObject();
			root.addProperty("errcode", "9527");
			root.addProperty("errmsg", "appid为null");
			return root.toString();
		}
		boolean isPerformanceTest = getContext().getServiceUtil().getConfiguration()
				.getBoolean(IPreferences.IS_PERFORMANCE_TEST, Boolean.FALSE);
		if (isPerformanceTest) {
			JsonObject root = new JsonObject();
			root.addProperty("errcode", "0");
			root.addProperty("errmsg", "ok");
			return root.toString();
		}
		logger.info("调用腾讯客服接口发送信息，APPID：{}，发送内容：{}。", appId, message);
		String baseUrl = MESSAGE_CUSTOM_SEND;
//		String baseUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send";
		Map<String, String> reqParams = new HashMap<String, String>();
		Map<String, String> companyInfo = getCompanyInfo(appId);
		logger.info("授权公众号信息：{}。", companyInfo);
		reqParams.put("access_token", companyInfo.get("authorizer_access_token"));
		String result = executePost(baseUrl, reqParams, message);
		Map<String, String> resultMap = result2Map(result);
		String errcode = resultMap.get("errcode");
		String success = "0".equals(errcode) ? "成功" : "失败";
		long t2 = System.currentTimeMillis();
		logger.info("调用腾讯客服接口发送信息，结果：{}，返回信息：{}，本次通讯耗时：{}毫秒。", success, result, (t2 - t1));
		return result;
	}
}
